import 'dart:convert';

import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/widgets.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:photo_frame/main.dart';
import 'package:photo_frame/net/http_manager.dart';
import 'package:photo_frame/provider/schedule_provider.dart';
import 'package:photo_frame/provider/users_provider.dart';
import 'package:photo_frame/user/user_manager.dart';
import 'package:photo_frame/utils/a_logger.dart';
import 'package:photo_frame/utils/localization_util.dart';
import 'package:provider/provider.dart';

class FCM {
  FCM._privateConstructor();

  static final FCM _instance = FCM._privateConstructor();

  factory FCM() {
    return _instance;
  }

  init() async {
    ALogger.d("FCM** Messaging init");

    // 请求通知权限
    FirebaseMessaging messaging = FirebaseMessaging.instance;
    NotificationSettings settings = await messaging.requestPermission(
      alert: true,
      badge: true,
      sound: true,
    );

    if (settings.authorizationStatus == AuthorizationStatus.authorized) {
      print('用户已授权通知权限');
    } else if (settings.authorizationStatus ==
        AuthorizationStatus.provisional) {
      print('用户暂时授权通知权限');
    } else {
      print('用户拒绝通知权限');
    }
    bindToken();
    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      print('FCM** Got a message whilst in the foreground!');
      print('FCM** Message : ${message.toMap()}');
      print('FCM** Message data: ${message.data}');
      int? type = int.tryParse(message.data['type'] ?? "");
      var data = message.data['message'];
      if (type == 1) {
        print('FCM** Message data-parse-type: ${type}');
        handleCustomMessage(data);
      } else if (type == 2) {
        handleOperationMessage(data);
      }
      if (message.notification != null) {
        print(
            'FCM** Message also contained a notification: ${message.notification}');
      }
    });
  }

  bindToken() {
    String? userToken = UserManager.instance.getToken();
    if (userToken?.isNotEmpty != true) {
      return;
    }
    FirebaseMessaging.instance.getToken().then((fcmToken) {
      ALogger.d("FCM** Messaging token: $fcmToken");
      HttpManager.instance.doRequest("/api/fcmreg",
          parameters: {"token": fcmToken}).then((e) async {
        if (!e.isSuccess) {
          Fluttertoast.showToast(msg: e.msg ?? "");
        }
      }).catchError((e) {
        ALogger.e("pushRegisterFail");
      });
    }).catchError((error) {
      print(error);
    });
  }

  handleCustomMessage(message) {
    try {
      Map<String, dynamic> map = jsonDecode(message);
      ALogger.e("handleCustomMessage ${map['id'].runtimeType}");
      int? id = map['id'];
      if (id == 1) {
        ALogger.e("handleCustomMessage 1");
      }
      switch (id) {
        //16. 添加日历参与者
        // 17. 删除日历参与者
        // 18. 修改日历参与者
        case 1:
          ALogger.e("handleCustomMessage 1");
          App.globalCxt
              .read<UsersViewModel>()
              .fetch(App.globalCxt.read<ScheduleViewModel>().lastFrameId ?? "");
          break;
        //20. 添加事件
        // 23. 修改事件
        // 24. 删除事件
        case 2:
          App.globalCxt
              .read<UsersViewModel>()
              .fetch(App.globalCxt.read<ScheduleViewModel>().lastFrameId ?? "");
          break;
        //34. 创建目录
        // 35. 重命名目录
        // 36. 删除目录
        case 5:
          break;
      }
    } catch (e) {
      print(e);
    }
  }

  handleOperationMessage(message) {}
}
